package com.myk.game.gobangchess.ai.finalsametimegobang;

import com.myk.game.gobangchess.constants.AppConfig;
import com.myk.game.gobangchess.utils.GridsUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class AiTransfer {

    private static ServerSocket serverSocket;
    private static int[] aiMovePoint;

    public static int[] getAiMovePoint(int[][] board, int turnType, int difficulty) {
        //初始化socket监听
        if(serverSocket == null){
            try {
                serverSocket = new ServerSocket(Integer.parseInt(AppConfig.AI_SERVER_PORT));
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        //开启线程，开启一个监听
        inisSocketListen(board, turnType, difficulty);

        //阻塞等待aiMovePoint有值
        while (aiMovePoint == null) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return aiMovePoint;
    }

    private static void inisSocketListen(int[][] board, int turnType, int difficulty) {
        aiMovePoint = null;
        //开启线程，开启一个http监听
        new Thread(() -> {
            try {
                Socket clientSocket = serverSocket.accept();
                DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream());
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                String outStr = GridsUtils.grids2Str(board) + "," + turnType + "," + difficulty;
                //String outStr = "11,1,1";
                //System.out.println("outStr消息：" + outStr);
                dos.writeUTF(outStr); //传board，turnType，difficulty给客户端
                String received = in.readLine();
                //System.out.println("received消息：" + received);
                if (received == null) return;
                received = received.replace("(", "").replace(")", "").replace(" ","");
                String[] receivedArr = received.split(",");
                aiMovePoint = new int[]{Integer.parseInt(receivedArr[0]), Integer.parseInt(receivedArr[1]),};
            }
            catch (Exception e) {
                throw new RuntimeException(e);
            }
            finally {
                try {
                    serverSocket.close();
                    serverSocket = null;
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
